package org.gntc.prayer.db;

import org.gntc.prayer.db.PrayerDBInfo.AnswerTBL;
import org.gntc.prayer.db.PrayerDBInfo.CategoryTBL;
import org.gntc.prayer.db.PrayerDBInfo.PrayerTBL;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class DBConnection
{
	private static final String DATABASE_NAME = "prayer.db";
	private static final int DATABASE_VERSION = 1;
	
	private Context m_context;
	private SQLiteDatabase m_DB;
	private PryaerDBHelper m_DBHelper;
	
	/**
	 * INNER CLASS : PryaerDBHelper
	 */
	private class PryaerDBHelper extends SQLiteOpenHelper
	{
		private static final String FOREIGNKEY_ON_CMD = "PRAGMA foreign_keys = ON;";
		
		/**
		 * PryaerDBHelper 생성자
		 */
		public PryaerDBHelper(Context context,
							  String name,
							  CursorFactory factory,
							  int version)
		{
			super(context, name, factory, version);
		}

		/**
		 * onCreate
		 */
		@Override
		public void onCreate(SQLiteDatabase db)
		{
			// Foreign key 설정
			db.execSQL(FOREIGNKEY_ON_CMD);
			
			// 카테고리 테이블 생성
			db.execSQL(CategoryTBL.CREATE_CATEGORY_TBL);
			
			// 내 기도 제목 테이블 생성
			db.execSQL(PrayerTBL.CREATE_PRAYER_TBL);
			
			// 응답 테이블 생성
			db.execSQL(AnswerTBL.CREATE_ANSWER_TBL);
			
			m_DB = db;
			
			// 기본 카테고리 생성
			initCategoryName();
		}

		/**
		 * onUpgrade
		 */
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
		{
			// 카테고리 테이블 삭제
			db.execSQL(CategoryTBL.DROP_CATEGORY_TBL);
			
			// 내 기도 제목 테이블 삭제
			db.execSQL(PrayerTBL.DROP_PRAYER_TBL);
			
			// 테이블 새로 생성
			onCreate(db);
		}
		
		/**
		 * 기본 카테고리 생성
		 */
		private void initCategoryName()
		{
			String[] category_name = m_context.getResources().getStringArray(org.gntc.prayer.R.array.category_name);
			
			for (String name : category_name)
			{
				ContentValues values = new ContentValues();
				values.put(CategoryTBL.COL_NAME, name);
				
				m_DB.insertOrThrow(PrayerDBInfo.CATEGORY_TABLE_NAME, null, values);
			}
		}
	}
	
	/**
	 * 생성자
	 * @param context
	 */
	public DBConnection(Context context)
	{
		m_context = context;
	}
	
	/**
	 * DB Open
	 * @return Instance of PrayerDBMngr
	 * @throws SQLiteException
	 */
	public DBConnection open() throws SQLiteException
	{
		// DB Helper 생성
		m_DBHelper = new PryaerDBHelper(m_context, DATABASE_NAME, null, DATABASE_VERSION);
		
		// DB 파일 생성 및 객체 얻기
		m_DB = m_DBHelper.getWritableDatabase();
		
		return this;
	}
	
	/**
	 * DB Close
	 */
	public void close()
	{
		m_DB.close();
	}

	/**
	 * Get DB
	 * @return
	 */
	public SQLiteDatabase getM_DB()
	{
		return m_DB;
	}
}
